package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersConfirmDTO;
import com.sky.dto.OrdersCancelDTO;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersRejectionDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.properties.ShopProperties;
import com.sky.service.OrdersService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Collectors;
import java.util.Map;

@Slf4j
@Service
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private OrderDetailMapper detailMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;

	@Autowired
	private ShopProperties shopProperties;

	@Value("${sky.baidu.baidu-url}")
	private String baiduUrl;

	@Value("${sky.baidu.riding-url}")
	private String ridingUrl;

    /**
     * 用户下单
     * @param dto
     */
    @Transactional  //0.开启事务
    public OrderSubmitVO submit(OrdersSubmitDTO dto) {
        //获取当前登陆人id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //获取地址（根据地址id查询）
        AddressBook addressBook = addressBookMapper.getById(dto.getAddressBookId());
        if (addressBook == null) {
            throw new OrderBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        //获取购物车列表数据（根据用户id查询当前登陆人的购物车数据）
        List<ShoppingCart> cartList = shoppingCartMapper.getByUserId(userId);
        if (cartList == null || cartList.isEmpty()) {
            throw new OrderBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

		//优化用户下单功能，加入校验逻辑，如果用户的收货地址距离商家门店超出配送范围（配送范围为5公里内），则下单失败。
		if (!checkRange(addressBook.getProvinceName()+addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail())) {
			throw new OrderBusinessException(MessageConstant.OUTTRANGE);
		}


        //1. 构造订单基本数据，存入orders表
        Orders orders = new Orders();
        BeanUtils.copyProperties(dto, orders);
        //1.1 需要补充其他字段数据
        orders.setNumber(String.valueOf(System.currentTimeMillis()));       //订单号
        orders.setStatus(Orders.PENDING_PAYMENT);                           //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消 7退款
        orders.setUserId(userId);                                           //用户id
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayMethod(1);                         //支付方式 1微信，2支付宝
        orders.setPayStatus(Orders.UN_PAID);            //支付状态 0未支付 1已支付 2退款
        orders.setPhone(addressBook.getPhone());        //收货人手机号
        orders.setAddress(addressBook.getDetail());     //收货地址
        orders.setUserName(user.getName());                 //下单人
        orders.setConsignee(addressBook.getConsignee());    //收货人
        //1.2 插入数据到表中
        ordersMapper.insert(orders);
        log.info("订单id: {}", orders.getId());

        //2.构造订单明细数据，存入order_detail表
        //注意：订单明细数据其实就是从购物车中取出商品数据存入明细表中
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart shoppingCart : cartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail, "id");
            //补充orderId
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
        detailMapper.insertBatch(orderDetailList);

        //3.清空购物车
        shoppingCartMapper.deleteByUserId(userId);

        //4.封装OrderSubmitVO数据，并返回
        return OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();
    }


    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // // 当前登录用户id
        // Long userId = BaseContext.getCurrentId();
        // User user = userMapper.getById(userId);
        //
        // //调用微信支付接口，生成预支付交易单
        // JSONObject jsonObject = weChatPayUtil.pay(
        //         ordersPaymentDTO.getOrderNumber(), //商户订单号
        //         new BigDecimal(0.01), //支付金额，单位 元
        //         "苍穹外卖订单", //商品描述
        //         user.getOpenid() //微信用户的openid
        // );
        //
        // if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
        //     throw new OrderBusinessException("该订单已支付");
        // }
        //
        // OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        // vo.setPackageStr(jsonObject.getString("package"));

        // 由于没有匹配的商户id，所以微信支付并不能调用成功，为了模拟成功的结果，所以直接返回成功结果。但是，需要修改订单状态
        // 订单状态：修改为待接单、支付状态：修改为已支付
        paySuccess(ordersPaymentDTO.getOrderNumber());

        return new OrderPaymentVO();
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo 订单号
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = ordersMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)         //订单状态：修改为待接单
                .payStatus(Orders.PAID)                 //支付状态：修改为已支付
                .checkoutTime(LocalDateTime.now())
                .build();

        ordersMapper.update(orders);
    }

    /**
     * 拒单
     *
     * @param ordersRejectionDTO
     */
    @Override
    public void adminRejection(OrdersRejectionDTO ordersRejectionDTO) {
        //判断有没有填写拒单原因
        if(ordersRejectionDTO.getRejectionReason().isEmpty()){
            throw new OrderBusinessException(MessageConstant.UNKNOWN_ERROR);
        }
        Orders ordersDB = ordersMapper.getById(ordersRejectionDTO.getId());
        //只有订单为待接单才能执行拒单操作
        if(!ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // TODO: 2024/1/2 暂时跳过微信退款接口，直接修改订单状态的代码
        log.warn("跳过了微信退款功能");
//        weChatRefundVerify(ordersDB);
        //修改订单状态为已取消,并设置取消原因和取消时间
        Orders orders = Orders.builder()
                .id(ordersRejectionDTO.getId())
                .status(Orders.CANCELLED)
                .rejectionReason(ordersRejectionDTO.getRejectionReason())
                .cancelTime(LocalDateTime.now())
                .payStatus(ordersDB.getPayStatus())
                .build();
        ordersMapper.update(orders);
    }

    /**
     * 取消订单
     *
     * @param ordersCancelDTO
     */
    @Override
    public void adminCancel(OrdersCancelDTO ordersCancelDTO) {
        //根据id查询订单
        Orders ordersDB = ordersMapper.getById(ordersCancelDTO.getId());
        // TODO: 2024/1/2 暂时跳过微信退款接口，直接修改订单状态的代码
        log.warn("跳过了微信退款功能");
//        weChatRefundVerify(ordersDB);
        //修改订单状态为已取消,并设置取消原因和取消时间
        Orders orders = Orders.builder()
                .id(ordersCancelDTO.getId())
                .status(Orders.CANCELLED)
                .cancelReason(ordersCancelDTO.getCancelReason())
                .cancelTime(LocalDateTime.now())
                .payStatus(ordersDB.getPayStatus())
                .build();
        ordersMapper.update(orders);
    }

    /**
     * 商家派送订单
     *
     * @param id
     */
    @Override
    public void delivery(Long id) {
        //根据id查询订单
        Orders ordersDB = ordersMapper.getById(id);
        //只有订单为待派送才能执行派送操作
        if(ordersDB == null || !ordersDB.getStatus().equals(Orders.CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.DELIVERY_IN_PROGRESS)
                .build();
        ordersMapper.update(orders);
    }
    /**
     *完成订单
     */
    public void complete(Long id) {
        // 根据id查询订单
        Orders ordersDB = ordersMapper.getById(id);

        // 校验订单是否存在，并且状态为4
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.COMPLETED)
                .build();
        ordersMapper.update(orders);
    }

    /**
     * 历史订单查询
     *
     * @param pageNum
     * @param pageSize
     * @param status
     * @return
     */
    @Override
    public PageResult pageQuery4User(int pageNum, int pageSize, Integer status) {
        // 设置分页
        PageHelper.startPage(pageNum,pageSize);
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);
        // 分页条件查询
        Page<Orders> page = ordersMapper.pageQuery(ordersPageQueryDTO);
        List<OrderVO> list = new ArrayList<>();
        // 查询出订单明细，并封装入OrderVO进行响应
        if (page != null && page.getTotal() > 0){
            for (Orders orders : page) {
                Long orderId = orders.getId();  //订单id
                // 查询订单明细
                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders,orderVO);
                orderVO.setOrderDetailList(orderDetails);
                list.add(orderVO);
            }
        }
        return new PageResult(page.getTotal(),list);
    }

    /**
     * 查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO details(Long id) {
        //根据id查询订单
        Orders orders = ordersMapper.getById(id);
        //查询该订单对应的菜品/套餐明细
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());
        //将该订单及其详情封装到OrderVO并返回
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);
        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }

    /**
     * 取消订单
     * @param id
     */
    @Override
    public void userCancelById(Long id) throws Exception {
        //根据id查询订单
        Orders ordersDB = ordersMapper.getById(id);
        //校验订单是否存在
        if (ordersDB == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (ordersDB.getStatus() > 2){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        //订单处于接单状态下取消，需要进行退款
        if (ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)){
            //调用微信支付退款接口
//            weChatPayUtil.refund(
//                    ordersDB.getNumber(),   //商户订单号
//                    ordersDB.getNumber(),   //商户退款号
//                    new BigDecimal(0.01),   //退款金额，单位 元
//                    new BigDecimal(0.01)    //原订单金额
//            );
            //支付状态修改为 退款
            orders.setPayStatus(Orders.REFUND);
        }
        //更新订单状态、取消原因、取消时间
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        ordersMapper.update(orders);
    }

    @Override
    public void repetition(Long id) {
        //查询当前用户id
        Long userId = BaseContext.getCurrentId();
        //根据订单id查询当前订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);
        //将订单详情对象转化为购物车对象
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(x -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            //将原订单详情里面的菜品信息重新复制到购物车对象中
            BeanUtils.copyProperties(x, shoppingCart, "id");
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());
        //将购物车对象批量添加到数据库
        shoppingCartMapper.insertBatch(shoppingCartList);
    }


	/**
	 * 检测配送距离是否超出范围
	 * @param address
	 * @return
	 */
	public boolean checkRange(String address){
		//店铺的经纬度
		Map params = new LinkedHashMap<String, String>();
		params.put("address", shopProperties.getAddress()); //店铺地址
		params.put("output", "json");   //输出格式为json
		params.put("ak", shopProperties.getAk());
		//得到对应的位置坐标
		String addressJson = HttpClientUtil.doGet(baiduUrl,params);
		//解析位置坐标得到店铺的经纬度的JSON串
		JSONObject jsonObject = JSON.parseObject(addressJson);//{result:location:lng,lat}
		//取得JSON串中的result中的经纬度坐标location
		JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
		//经度值 float
		Object lng = location.get("lng");
		//纬度值 float
		Object lat = location.get("lat");
		//拼接店铺的纬经度
		String origin = lat + "," + lng;

		//外卖地址的经纬度
		Map myParams = new LinkedHashMap<String, String>();
		myParams.put("address",address); //店铺地址
		myParams.put("output", "json");   //输出格式为json
		myParams.put("ak", shopProperties.getAk());
		//得到对应的位置坐标
		String myAddressJson = HttpClientUtil.doGet(baiduUrl,myParams);
		//解析位置坐标得到店铺的经纬度的JSON串
		JSONObject myJsonObject = JSON.parseObject(myAddressJson);//{result:location:lng,lat}
		//取得JSON串中的result中的经纬度坐标location
		JSONObject myLocation = myJsonObject.getJSONObject("result").getJSONObject("location");
		//经度值 float
		Object myLng = myLocation.get("lng");
		//纬度值 float
		Object myLat = myLocation.get("lat");
		//拼接外卖地址的纬经度
		String destination = myLat + "," + myLng;

		//计算相差的距离
		Map lenMap = new LinkedHashMap<String, String>();
		lenMap.put("origin",origin);
		lenMap.put("destination", destination);
		lenMap.put("ak", shopProperties.getAk());
		//得到两地之间的路线JSON字符串
		String lengthJson = HttpClientUtil.doGet(ridingUrl,lenMap);
		JSONObject jsonObjectLen = JSON.parseObject(lengthJson);
		//超出省了，直接解析失败
		if (!jsonObjectLen.get("status").equals(0)){
			return false;
		}
		//得到路线JSON字符串中的routes
		JSONArray routes = jsonObjectLen.getJSONObject("result").getJSONArray("routes");
		//得到routes中的方案距离，单位：米
		Integer distance = (Integer) routes.getJSONObject(0).get("distance");
		log.info("两地之间的距离为{}米",distance);

		return distance <= shopProperties.getDistance();
	}
    /**
     * 订单搜索
     *
     * @param ordersPageQueryDTO
     * @return
     */

    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());

        Page<Orders> page = ordersMapper.pageQuery(ordersPageQueryDTO);


        List<OrderVO> orderVOList = getOrderVOList(page);

        return new PageResult(page.getTotal(), orderVOList);
    }

    private List<OrderVO> getOrderVOList(Page<Orders> page) {

        List<OrderVO> orderVOList = new ArrayList<>();

        List<Orders> ordersList = page.getResult();
        if (!CollectionUtils.isEmpty(ordersList)) {
            for (Orders orders : ordersList) {

                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                String orderDishes = getOrderDishesStr(orders);


                orderVO.setOrderDishes(orderDishes);
                orderVOList.add(orderVO);
            }
        }
        return orderVOList;
    }

    /**
     * 根据订单id获取菜品信息字符串
     *
     * @param orders
     * @return
     */
    private String getOrderDishesStr(Orders orders) {

        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());


        List<String> orderDishList = orderDetailList.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());


        return String.join("", orderDishList);
    }

    /**
     * 各个状态的订单数量统计
     * @return
     */
    @Override
    public OrderStatisticsVO orderQuantityStatistics() {
        Integer toBeConfirmed = ordersMapper.byStatus(Orders.TO_BE_CONFIRMED); //待接单
        Integer confirmed = ordersMapper.byStatus(Orders.CONFIRMED);//已接单
        Integer deliveryInProgress = ordersMapper.byStatus(Orders.DELIVERY_IN_PROGRESS);//派送中

        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }

    /**
     * 接单
     *
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(ordersConfirmDTO.getStatus())
                .build();

        ordersMapper.update2(orders);
    }
}
